package com.we823.cms.core.security.shiro.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.we823.cms.common.WebConstants;
import com.we823.cms.model.sys.User;
import com.we823.cms.repository.service.sys.UserService;

/**
 * Created by ZhangYinxian on 2014/12/5.
 */
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {
    private Logger logger = LoggerFactory.getLogger(CustomFormAuthenticationFilter.class);
    @Autowired
    private UserService userService;
    
    private String defaultSuccessUrl;
    private String defaultAdminSuccessUrl;

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public String getDefaultSuccessUrl() {
        return defaultSuccessUrl;
    }

    public void setDefaultSuccessUrl(String defaultSuccessUrl) {
        this.defaultSuccessUrl = defaultSuccessUrl;
    }

    public String getDefaultAdminSuccessUrl() {
        return defaultAdminSuccessUrl;
    }

    public void setDefaultAdminSuccessUrl(String defaultAdminSuccessUrl) {
        this.defaultAdminSuccessUrl = defaultAdminSuccessUrl;
    }

    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        logger.debug("onPreHandle");

        boolean isAccessAllowed = isAccessAllowed(request, response, mappedValue);

        logger.debug("isAccessAllowed:{}", isAccessAllowed);
        if (isAccessAllowed && isLoginRequest(request, response)) {
            try {
                issueSuccessRedirect(request, response);
            } catch (Exception e) {
                logger.error("{}", e);
            }
            return false;
        }
        return isAccessAllowed || onAccessDenied(request, response, mappedValue);
    }

    @Override
    protected void setFailureAttribute(ServletRequest request, AuthenticationException ae) {
        request.setAttribute(getFailureKeyAttribute(),ae);
    }

    @Override
    public String getSuccessUrl() {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        User userModel = userService.findByUsername(username);
        
        if(userModel!=null && userModel.getAdmin()==1){
        	
        	Subject subject = SecurityUtils.getSubject();
        	Session session = subject.getSession();
        	session.setAttribute(WebConstants.CURRENT_USER, userModel);
            return  getDefaultAdminSuccessUrl();
        }
        return getDefaultSuccessUrl();
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        logger.debug("onLoginSucccess");

        Session session = subject.getSession();
        session.setAttribute("logining", 1);
        session.setAttribute("username", token.getPrincipal());
        

        return super.onLoginSuccess(token, subject, request, response);
    }
}
